/* eslint-disable object-curly-spacing */

export class ModelClass {
  _records = []

  constructor({ model, env, rpc }) {
    this.env = env
    this.rpc = rpc
  }

  // 处理计算列
  _format_record(rec) {
    return rec
  }

  search(payload) {
    return [...this._records].reverse().map(item => this._format_record(item))
  }

  _search_one(payload) {
    const fn_boolean = (record, domain) => {
      const booleanValue = Object.keys(domain).reduce((acc, cur) => {
        acc = acc && domain[cur] === record[cur]
        return acc
      }, true)
      return booleanValue
    }

    const { domain } = payload
    const recs = this._records.filter(item => fn_boolean(item, domain))
    const rec = recs.length ? recs[0] : {}
    return rec
  }

  search_one(payload) {
    const rec = this._search_one(payload)
    return this._format_record(rec)
  }

  browse(rids = [], kwargs = {}) {
    // console.log('browse_one,', rid, kwargs)
    return this._records.filter(item => rids.includes(item.id))
  }

  lookup(rid, kwargs) {
    // console.log('browse_one,', rid, kwargs)
    return this._search_one({ domain: { id: rid } })
  }

  browse_one(rid, kwargs) {
    // console.log('browse_one,', rid, kwargs)
    return this.search_one({ domain: { id: rid } })
  }

  create(payload) {
    //
    const { values } = payload
    let ids = this._records.map(item => item.id)
    ids = [...ids, 0]
    const newId = Math.max(...ids) + 1
    const rec = { id: newId, ...values }
    this._records.push(rec)
    return rec
  }

  unlink(rid) {
    //
    const index = this._records.findIndex(item => item.id === rid)
    if (index >= 0) {
      this._records.splice(index, 1)
      return true
    } else {
      return false
    }
  }

  write(payload) {
    const { values } = payload
    const rid = values.id

    const rec = this._search_one({ domain: { id: rid } })
    Object.keys(values).forEach(item => {
      rec[item] = values[item]
    })

    return rec
  }

  update_or_create(payload) {
    console.log('update_or_create, ', payload)
    const { values, domain } = payload

    if (domain) {
      const rec = this._search_one({ domain })
      if (rec.id) {
        return this.write({
          values: {
            id: rec.id,
            ...values
          }
        })
      } else {
        return this.create(payload)
      }
    } else {
      return this.write({ values })
    }
  }
}
